#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import random
import re

import FileHostProtoType


class rsitem(FileHostProtoType.HostItem):
    pass

class ryushare(FileHostProtoType.FileHostProcess):   
    HOST_URL = "http://ryushare.com/"
    ACCOUNT_URL = "http://ryushare.com/my-account.python"  
             
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "RyuShare" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'
        self._cookieCurl = self._user + '_%s.cookie' % self.hostname
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
                
    def login(self):        
        self.generateOpener()
        if self.restore_cookiejar():
            return True
        self.fherr.write('login to %s %s/%s...' % (self.hostname, self._user,'*'*len(self._pwd)))
        loginData = {'login' : self._user, 
                     'password' : self._pwd,
                     'loginFormSubmit' : 'Login',
                     'op' : 'login',
                     'redirect' : self.ACCOUNT_URL,
                     }
        loginresult =  self.loginFileHost(
                    self.HOST_URL, 
                    loginData
                    )
        # you always see you username at the top of the page, if login successfully.
        if not self.check_cookie():
            self.fherr.write("User %s Failed to Login MegaUpload." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self._cj.save(self._cookieCurl, ignore_discard=True)
        self.islogin = True
        return True
    
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False  

    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request(self.ACCOUNT_URL)
        if response and "http://ryushare.com/users/" + self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        self.fherr.write(response)
        return False
        
    def get_random(self):
        times = 3
        randstr = ''
        while times > 0:
            randstr += '%04d' % (random.randint(0,9999))
            times -= 1
        return randstr
            
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        data ={}
        indexpage = self.post_request(self.HOST_URL)
        
        keys = ['sess_id','upload_type','srv_tmp_url']
        for k in keys:
            v = self.get_upload_key(indexpage, 'name="%s"' % k, -2)
            data[k] = v
        data["tos"] = '1'
        data['submit_btn'] = 'Upload!'
        
        server = self.get_upload_key(indexpage, 'return StartUpload', 5)
        upload_link = server + "%s&js_on=1&utype=reg&upload_type=file" % self.get_random()
                            
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        fileobj = open(file, 'rb')
        fileobj.seek(start_point) 
        data['file_0'] = fileobj
        
        self.fherr.write(info)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_link, data, retry=1, cb=callback, setfilename=filename, setfilesize=filesize)
        #result#
        if "OK" in result:
            s_pos = result.find("'fn'>")
            if s_pos == -1:
                self.fherr.write("Failed to get uploaded file id.")
                self.fherr.write(result)
                return
            e_pos = result.find("<", s_pos)
            file_id = result[s_pos+5:e_pos]
            if re.compile('^[0-9A-Za-z]+$').match(file_id) is not None:
                filelink = self.HOST_URL + file_id + "#" + filename
                item = rsitem(os.path.basename(file), 'file', file_id, filelink, filename)
                self.newupload.append(item)
                self.fhout.write(item.format()) 
                return item
        
        self.fherr.write("Failed to upload?")
        self.fherr.write(result)